package com.example.yian.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.yian.entity.SecurityRisk;
import com.example.yian.entity.SecurityRiskReport;
import com.example.yian.entity.TextSearchRequest;
import com.example.yian.entity.TextSearchResponse;
import com.example.yian.service.TextSearchService;
import com.example.yian.service.WeChatAuthService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.util.*;

@RestController
public class TextSearchController {

    @Autowired
    private TextSearchService textSearchService;

    private static String strNewApiKey = "application-1dabbbdbf2be09c946ef401ca2412fdb";

    private static String strNewChatId = "c95507ba-93a4-11ef-a11d-0242ac110002";

    private static String strOldApiKey = "application-8900dd45b50a0e7d2b06bef61c526df0";

    private static String strOldChatId = "2f611eda-93a6-11ef-ad48-0242ac110002";

    @Autowired
    private WeChatAuthService weChatAuthService;

    private static final Logger log = LoggerFactory.getLogger(SecurityRiskController.class);

    @PostMapping("/textSearch")
    public Map<String, Object> handleTextSearch(@RequestHeader("Authorization") String token, @RequestBody Map<String, String> requestBody) {
        Map<String, Object> response = new HashMap<>();
        Optional<Long> userIdOpt = weChatAuthService.getUserIdFromToken(token);
        if (userIdOpt.isEmpty()) {
            response.put("code", 401);
            response.put("msg", "登录过期");
            response.put("time", Instant.now().toEpochMilli());
            response.put("data", new HashMap<>());
            return response;
        }
        String textMessage = requestBody.get("textMessage");
        Boolean reChat = false;
        Boolean stream = false;

        Boolean is_save = Boolean.valueOf(requestBody.get("isSave"));
        // 创建请求记录
        TextSearchRequest request = textSearchService.createRequest(textMessage, reChat, stream, userIdOpt.get(),is_save);
        String chatId = "";//"5261ef24-1cf8-11ef-bbae-0242ac110002";
        if(is_save)
        {
            chatId = strOldChatId;
        }
        else {
            chatId = strNewChatId;
        }
        // 调用第三方接口并获取应答数据
        Map<String, Object> thirdPartyResponse = textSearchService.callThirdPartyApi(chatId, textMessage, reChat, stream, is_save);
        Map<String, Object> data = (Map<String, Object>) thirdPartyResponse.get("data");

        // String chatId = (String) data.get("chat_id");
        String textId = (String) data.get("id");

        log.info("textSearch | textId: {}", textId);
        Boolean operate = (Boolean) data.get("operate");
        String content = (String) data.get("content");
        Boolean isEnd = (Boolean) data.get("is_end");
        String refText = "GB50310电梯工程施工质量验收"; // 示例引用文本
        // 创建应答记录
        TextSearchResponse textSearchResponse = textSearchService.createResponse(request.getId(), chatId, textId, operate, content, refText, isEnd,is_save);
        response.put("code", 200);
        response.put("message", "成功");
        response.put("time", Instant.now().toEpochMilli());
        response.put("data", textSearchResponse);
        return response;
    }

    @PostMapping("/getSpecificationHisSearch")
    public Map<String, Object> handleGetSepcificationHisSearch(@RequestHeader("Authorization") String token, @RequestBody Map<String, Object> requestBody)
    {
        Map<String, Object> response = new HashMap<>();
        Optional<Long> userIdOpt = weChatAuthService.getUserIdFromToken(token);
        if (userIdOpt.isEmpty()) {
            response.put("code", 401);
            response.put("msg", "登录过期");
            response.put("time", Instant.now().toEpochMilli());
            response.put("data", new HashMap<>());
            return response;
        }

        Long userId = userIdOpt.get();
        //Long userId = 23L;
        // 从请求体中提取分页参数
        Integer pageNum = (Integer) requestBody.getOrDefault("page", 1);
        Integer pageSize = (Integer) requestBody.getOrDefault("size", 1000);
        String  startTime = (String) requestBody.getOrDefault("startTime", "2024-03-03");
        if (Objects.equals(startTime, "")) {
            startTime = (String) "2024-03-03";
        }
        String endTime = (String) requestBody.getOrDefault("endTime", "2099-08-15");
        if (Objects.equals(endTime, "")) {
            endTime = (String) "2099-08-15";
        }

        Page<SecurityRisk> page = new Page<>(pageNum, pageSize);
        IPage<TextSearchRequest> specificationSearchPage = textSearchService.getSearchRequstByUserIdWithPagination(userId, pageNum, pageSize,true, startTime,endTime);
        response.put("code", 200);
        response.put("msg", "成功");
        response.put("time", Instant.now().toEpochMilli());
        response.put("total", specificationSearchPage.getTotal());

        //重新拿取一把
        List<TextSearchRequest> sepcificationSearchList = specificationSearchPage.getRecords();

        if(sepcificationSearchList.size() == 0)
        {
            log.error("getSpecificationHisSearch | sepcificationSearchList is empty");
        }

        List<Map<String, Object>> dataWithExtraFields = new ArrayList<>();
        for (TextSearchRequest searchItem : sepcificationSearchList) {
            Map<String, Object> dataItem = new HashMap<>();
            dataItem.put("searchText",searchItem.getTextMessage());
            dataWithExtraFields.add(dataItem);
        }
        response.put("data",dataWithExtraFields);
        return response;

    }

    @PostMapping("/saveSearchText")
    public Map<String, Object> saveSearchText(@RequestHeader("Authorization") String token,@RequestBody Map<String, Object> requestBody) {
        Map<String, Object> response = new HashMap<>();
        Optional<Long> userIdOpt = weChatAuthService.getUserIdFromToken(token);
        if (userIdOpt.isEmpty()) {
            response.put("code", 401);
            response.put("msg", "登录过期");
            response.put("time", Instant.now().toEpochMilli());
            response.put("data", new HashMap<>());
            return response;
        }

        log.info("saveSearchText | enter save function");

        /*String textId = (String) requestBody.get("textId");
        Object contentObj = requestBody.get("content");
        String refText = (String) requestBody.get("refText");
        String chatId = (String) requestBody.get("chatId");
        String requestId = (String) requestBody.get("requestId");*/

        String textId = Optional.ofNullable(requestBody.get("textId")).map(Object::toString).orElse("");
       // String content = Optional.ofNullable(requestBody.get("content")).map(Object::toString).orElse("");
        Object contentObj = requestBody.get("content");
        String refText = Optional.ofNullable(requestBody.get("refText")).map(Object::toString).orElse("");
        String chatId = Optional.ofNullable(requestBody.get("chatId")).map(Object::toString).orElse("");
        String requestId = Optional.ofNullable(requestBody.get("requestId")).map(Object::toString).orElse("");
        log.info("saveSearchText | requestId: {}", requestId);
       // String isEndStr = (String) requestBody.get("isEnd");
        String isEndStr = "false";
        //String operate = (String) requestBody.get("operate");
        String operate = "true";
        String userId = (String) requestBody.get("userId");
        log.info("saveSearchText | enter function,textId:{ }",textId);
        // 将字符串数组拼接成一个字符串
        String content;
        if (contentObj instanceof List) {
            List<String> contentList = (List<String>) contentObj;
            content = String.join(" ", contentList);
        } else if (contentObj instanceof String[]) {
            String[] contentArray = (String[]) contentObj;
            content = String.join(" ", contentArray);
        } else {
            content = (String) contentObj;
        }

        log.info("saveSearchText | text_id : {}", textId);

        // 将 isEnd 转换为布尔值
        boolean isEnd = Boolean.parseBoolean(isEndStr);
        textSearchService.InsertTextSearchResponse(Long.valueOf(requestId), chatId, textId, true, content, refText, true);

        response.put("code", 200);
        response.put("message", "成功");
        response.put("time", Instant.now().toEpochMilli());
        response.put("data", new HashMap<>());
        return response;
    }

    @PostMapping("/textContent")
    public Map<String, Object> getTextContentByTokenAndTextId(
           // @RequestHeader("Authorization") String token,
            @RequestBody Map<String, String> requestBody) {

        Map<String, Object> response = new HashMap<>();

      //  log.info("textContent | auth:{}",token);
        // 验证token有效性
      /*  Optional<Long> userIdOpt = weChatAuthService.getUserIdFromToken(token);
        if (userIdOpt.isEmpty()) {
            response.put("code", 401);
            response.put("msg", "登录过期");
            response.put("time", Instant.now().toEpochMilli());
            response.put("data", new HashMap<>());
            return response;
        }*/
        // 从请求体中获取textId
        String textId = requestBody.get("textId");

        // 根据textId查询content和refText
        Optional<TextSearchResponse> textSearchResponseOpt = textSearchService.findByTextId(textId);

        log.info("textContent | textId:{}",textId);
        if (textSearchResponseOpt.isPresent()) {
            TextSearchResponse textSearchResponse = textSearchResponseOpt.get();
            Optional<TextSearchResponse> responseOpt = textSearchService.findByTextId(textId);
            if(responseOpt.isPresent()) {
                Optional<TextSearchRequest> requestOpt = textSearchService.findRequestById(responseOpt.get().getRequestId());
                String searchText = requestOpt.get().getTextMessage();
                response.put("searchText", searchText);
                log.info("textContent | get valid searchText!");
            }
            else
            {
                log.info("textContent | response not found, textId:{}",textId);
                response.put("searchText", "");
            }

            Map<String, Object> data = new HashMap<>();
            data.put("content", textSearchResponse.getContent());
            data.put("refText", textSearchResponse.getRefText());

            response.put("code", 200);
            response.put("message", "查询成功");
            response.put("time", Instant.now().toEpochMilli());
            response.put("data", data);
        } else {
            log.error("textContent | cannot find corresponed content!");
            response.put("code", 404);
            response.put("msg", "未找到对应内容");
            response.put("time", Instant.now().toEpochMilli());
            response.put("data", new HashMap<>());
        }

        return response;
    }

    @PostMapping("/localTextSearch")
    public Map<String, Object> handleLocalTextSearch(@RequestHeader("Authorization") String token, @RequestBody Map<String, String> requestBody) {
        Map<String, Object> response = new HashMap<>();
        Optional<Long> userIdOpt = weChatAuthService.getUserIdFromToken(token);
        if (userIdOpt.isEmpty()) {
            response.put("code", 401);
            response.put("msg", "登录过期");
            response.put("time", Instant.now().toEpochMilli());
            response.put("data", new HashMap<>());
            return response;
        }
        String textMessage = requestBody.get("textMessage");
        String tableName = "";
        Object tableIdObj = requestBody.get("tableId");
        if (tableIdObj != null) {
            int tableId = Integer.parseInt((String) tableIdObj);
            switch (tableId) {
                case 0:
                    tableName = "building_safetyphrases";
                    break;
                case 1:
                    tableName = "municipalengineering_safetyphrases";
                    break;
                default:
                    // 处理其他情况，例如日志记录或默认值
                    tableName = "building_safetyphrases";
                    break;
            }
        }

        Boolean reChat = false;
        Boolean stream = false;
        // 创建请求记录
        TextSearchRequest request = textSearchService.createRequest(textMessage, reChat, stream, userIdOpt.get(),false);
        String chatId = "5261ef24-1cf8-11ef-bbae-0242ac110003";
        chatId = strOldChatId;

        // 调用第三方接口并获取应答数据
        List<Map<String, Object>> thirdPartyResponse = textSearchService.callLocalSearchApi(chatId, textMessage, tableName, stream, false);
        String textId = UUID.randomUUID().toString();

        // 创建应答记录
        TextSearchResponse textSearchResponse = textSearchService.createResponse(request.getId(), chatId, textId, true, "", "", true,false);

        Map<String, Object> data = new HashMap<>();
        data.put("content", thirdPartyResponse);
        data.put("chatId", chatId);
        data.put("textId",textId);
        data.put("requestId", request.getId());

        response.put("code", 200);
        response.put("message", "成功");
        response.put("time", Instant.now().toEpochMilli());
        response.put("data", data);
        return response;
    }


}
